package com.chookss.home.audit.shop;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.audit.clockIn.ClockInUtils;
import com.chookss.home.entity.ClockInGroupEntity;
import com.chookss.home.entity.ReimbursementDetailEntity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.lvgroup.hospital.base.BaseAct;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShopProjecDeliveryActivity extends BaseAct {
    //物品项目交付
    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.tvGroup)
    TextView tvGroup;
    @BindView(R.id.edContent)
    EditText edContent;
    @BindView(R.id.tvSure)
    TextView tvSure;
    private String groupCode = "", groupName = "",goodsCode="";
    private List<ClockInGroupEntity> groupEntities = new ArrayList<>();
    private String[] groupArray = null;
    private ReimbursementDetailEntity reimbursementDetailEntity=null;
    private int source = 0;//0新增 1是修改
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_project_delivery);
        ButterKnife.bind(this);
        initState();
    }

    @Override
    public void initData() {
        commonTitleTxt.setText("项目交付");
        source = getIntent().getIntExtra("source", 0);
        goodsCode = getIntent().getStringExtra("goodsCode");
        if (source == 1) {
            tvSure.setText("重新提交");
        }
        getGroupList();
        selectGoodsInfDetail();

    }
    private void getGroupList() {
        //项目组基本数据
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<ClockInGroupEntity>>>() {
        }.getType(), null, Urls.selectItemGroupList, SignUtils2.makeSignStr(null), false, new ObserverCallback<List<ClockInGroupEntity>>() {
            @Override
            public void onSuccess(List<ClockInGroupEntity> data) {
                if (data != null && data.size() > 0) {
                    if (tvGroup == null) {
                        return;
                    }
                    groupEntities.addAll(data);
                    groupArray = new String[groupEntities.size()];
                    for (int i = 0; i < groupEntities.size(); i++) {
                        if ("1".equals(groupEntities.get(i).getMainCd())) {
                            groupArray[i] = groupEntities.get(i).getGroupName() + "[常驻]";
                        } else {
                            groupArray[i] = groupEntities.get(i).getGroupName();
                        }

                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    private void selectGoodsInfDetail() {
        //审批基本数据
        Map<String, String> map = new HashMap<>();
        map.put("projectCode", goodsCode);
        map.put("type", "8");   // 1-新闻 2-视频 3-补卡 4-请假 5-外勤 6-图文7报销8物料9借款
        showLoading();
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<ReimbursementDetailEntity>>() {
        }.getType(), null, Urls.selectKaoqinDeail, SignUtils2.makeSignStr(map), false, new ObserverCallback<ReimbursementDetailEntity>() {
            @Override
            public void onSuccess(ReimbursementDetailEntity data) {
                dismissLoading();
                if (data != null) {
                    if (edContent == null) {
                        return;
                    }
                    reimbursementDetailEntity = data;
//                    if(source==1){
//                        if(!Utils.isNull(data.getYcRemark())){
//                            edContent.setText(data.getYcRemark());
//                        }
//                        groupCode = data.getGroupCode();
//                        groupName = data.getGroupName();
//                        tvGroup.setText(groupName + "(" + ClockInUtils.getGroupEnd(groupCode) + ")");
//                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    private void updateGoodsStatus() {
        if(reimbursementDetailEntity==null){
            MyToast.show("数据异常，请稍后重试");
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("orgCode", reimbursementDetailEntity.getOrgCode());
        map.put("amt", reimbursementDetailEntity.getAmt());
        map.put("workflowId", reimbursementDetailEntity.getWorkflowId());
        map.put("goodsCode", goodsCode);
        map.put("goodsName", reimbursementDetailEntity.getGoodsName());
        map.put("goodsNum","1");
        map.put("groupCode", groupCode);
        map.put("groupName",groupName);
        map.put("baoixaoTypeCode", reimbursementDetailEntity.getBaoixaoTypeCode());
        map.put("baoxiaoTypeName", reimbursementDetailEntity.getBaoixaoTypeName());
        map.put("statusCd",   "7");
        map.put("ycRemark", edContent.getText().toString());
        showLoading();
        MyHttpRequest.postRequest(Urls.updateGoodsStatus, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("提交成功");
                        EventBus.getDefault().post(new MyEvent("RefreshShopRecord"));
                        finish();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("提交失败，请稍后重试");
                }
            }
        });
    }


    @OnClick({R.id.common_title_back, R.id.tvGroup, R.id.tvSure})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.tvGroup:
                if (groupArray == null) {
                    MyToast.show("无可选项目组，请联系管理员配置");
                    return;
                }
                new XPopup.Builder(ShopProjecDeliveryActivity.this)
                        .maxWidth(Utils.dip2px(ShopProjecDeliveryActivity.this, 260))
                        .maxHeight(Utils.dip2px(ShopProjecDeliveryActivity.this, 300))
                        .asCenterList("请选择项目组", groupArray,
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        groupCode = groupEntities.get(position).getGroupCode();
                                        groupName = groupEntities.get(position).getGroupName();
                                        tvGroup.setText(text.replace("[常驻]", "") + "(" + ClockInUtils.getGroupEnd(groupEntities.get(position).getGroupCode()) + ")");
                                    }
                                })
                        .show();
                break;
            case R.id.tvSure:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (Utils.isNull(groupCode)) {
                    MyToast.show("请先选择项目组");
                    return;
                }
                if (Utils.isNull(edContent.getText().toString())) {
                    MyToast.show("请输入备注");
                    return;
                }
                updateGoodsStatus();
                break;
        }
    }

}
